﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using AgFx;
using DepSoft.Mobile.WP7.FollwIt.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace DepSoft.Mobile.WP7.FollwIt.ViewModel
{
    /// <summary>
    /// We cache a Friends Collection for 1 hour ( 3600 secs )
    /// We do a cache then refresh, because this will give us following principle
    /// 1. App will make request, [A, B, C] will be returned from cache and displayed
    /// 2. AgFx will see that the cache is no longer valid (more than 3600 seconds have elapsed) and will kick off a new request
    /// 3. Server will return, say [C, D, E]
    /// 4. Cache will be replaced and UI will bind to new value
    /// </summary>
    [CachePolicy(CachePolicy.CacheThenRefresh, 3600)]
    public class agfxFriendsViewModel : ModelItemBase<UserProfileLoadContext>
    {
        #region Public bindable properties
        /// <summary>
        /// The <see cref="Friends" /> property's name.
        /// </summary>
        public const string FriendsPropertyName = "Friends";
        private BatchObservableCollection<Friend> _friends = new BatchObservableCollection<Friend>();

        /// <summary>
        /// Gets the Friends property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public ObservableCollection<Friend> Friends
        {
            get
            {
                return _friends;
            }

            set
            {
                if (!ReferenceEquals(_friends, null))
                {
                    _friends.Clear();

                    if (_friends != value)
                    {
                        foreach (var friend in value)
                        {
                            _friends.Add(friend);
                        }
                    }
                }
                RaisePropertyChanged(FriendsPropertyName);
            }
        }
        #endregion

        #region Constructor
        public agfxFriendsViewModel()
        {

        }

        public agfxFriendsViewModel(string userName)
            : base(new UserProfileLoadContext(userName))
        {

        }
        #endregion

        #region AgFx DataLoader
        public class agfxFriendsViewModelLoader : IDataLoader<UserProfileLoadContext>
        {
            #region IDataLoader implementation
            public object Deserialize(UserProfileLoadContext loadContext, Type objectType, Stream stream)
            {
                var sr = new StreamReader(stream);
                var userProfileJSON = sr.ReadToEnd();
                JObject userProfile = JObject.Parse(userProfileJSON);

                agfxFriendsViewModel viewModel = new agfxFriendsViewModel(loadContext.UserName);

                JsonSerializer serializer = new JsonSerializer();
                foreach (JToken friendJSon in userProfile["friends"])
                {
                    Friend friend = (Friend)serializer.Deserialize(new JTokenReader(friendJSon), typeof(Friend));

                    viewModel.Friends.Add(friend);
                    //viewModel.Friends.Add(friend);
                    //viewModel.Friends.Add(friend);
                }                

                return viewModel;
            }

            public LoadRequest GetLoadRequest(UserProfileLoadContext loadContext, Type objectType)
            {
                return new WebLoadRequest(loadContext, new Uri(FollwItApi.GetInstance().GetActionRestURI(RestAction.GetUserProfile, loadContext.UserName)));
            }
            #endregion
        }
        #endregion
    }
}